package com.example.demo.scheduler;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.stereotype.Component;

import com.example.demo.service.BookService;
import com.example.demo.service.JsonData;
import com.example.demo.service.OrderTicketBody;
import com.example.demo.service.ProductInfo;
import com.example.demo.service.UserInfo;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 杜云山
 * @date 22/06/01
 */
@Slf4j
@Component
public class RobBookingScheduler {

    private final BookService bookService;

    public final static String ORDER_URL = "https://zd1.zhiketong.com/Ticket/api?appid=wxbf9906647c6bfcbc&method=orderTicket";

    public final static String COOKIE_NAME = "wxbf9906647c6bfcbc_open_id";

    private final List<UserInfo> userInfos = Arrays.asList(
        new UserInfo("obzFh5JEm924S-ILCmrUwk2OQIoI||HZZJjpd8xD0g5OHHBUhGvw", "18622417826", "161981733", "杜伟")
        ,
        new UserInfo("obzFh5EBcQQeG02IPRHq70k6Cprw||kpDgG1PeVBAZfBlf3Y8fZQ", "13137853612", "184635462", "王大梅")
        ,
        new UserInfo("obzFh5HFaTTA1xD-VnZ0Jcpcltsg||loQjG4vKKVxKMqRLqDXQEQ", "15657185751", "204403372", "我")
        ,
        new UserInfo("obzFh5JD5BI0fUGF-3nQuDArduMc||KyAQTvrJZiiVKdO0EZOc3g", "15657185751", "294962685", "小号")
//        ,
//        new UserInfo("o4fTwwHjPeZ_1uVObGjKnclHLjiQ||mjA8feG3AEruDxX9ScfCuQ", "13381122520", "253654078", "伍新生")
    );

    private final List<ProductInfo> productInfos;
//
//    private final ProductInfo[] productInfos = {
//
//        new ProductInfo(2560D, "mini套餐C（面部护理+身体按摩）", "1695737", null),
//        new ProductInfo(2560D, "mini套餐C（面部护理+身体按摩）", "1695737", null),
////        new ProductInfo(150D, "粽子", "1891213"),
////        new ProductInfo(150D, "粽子", "1891213"),
////        new UserInfo("", "", "", ""),
////        new UserInfo("", "", "", ""),
////        new UserInfo("", "", "", ""),
//    };

    public RobBookingScheduler(BookService bookService) {

        this.bookService = bookService;

        productInfos = getJsonData()
            .stream()
            .map(e -> new ProductInfo(e.getSalePrice(), e.getProductName(), String.valueOf(e.getProductId()), shipType))
            .collect(Collectors.toList());

        CronExpression parse = CronExpression.parse(ROB_CRON);
        LocalDateTime next = parse.next(LocalDateTime.now());
        log.info("---------开启秒杀: {}---------", next);
        log.info("---------秒杀产品: {}---------", productInfos);
    }

    /**
     * 海湾6.18是10点抢
     *
     * <p>10点 00分 00秒: 00 00 10 * * ?
     */
    private final String ROB_CRON = "00 00 10 * * ?";

    // 粽子 "not_filled_now", 别的无需邮寄的 null
    String shipType = null;

    @Scheduled(cron = ROB_CRON)
//    @Scheduled(cron = "02 00 10 * * ?")
//    @Scheduled(initialDelay = 1, fixedDelay = 60000_000)
    public void book() {

        log.info("-----------------------定时任务开始执行");

        userInfos.stream()
            .parallel()
            .forEach(userInfo -> {

                // 如果是真正的 n*m 个请求, 这里不行,  需要外层n*m并行流
                for (ProductInfo productInfo : productInfos) {
                    book(userInfo, productInfo);
                }

            });

    }

    private void book(UserInfo userInfo, ProductInfo productInfo) {

        String mobile = userInfo.getMobile();
        String cookieValue = userInfo.getCookieValue();

        double fee = productInfo.getFee();
        String productName = productInfo.getProductName();
        String memberId = userInfo.getMemberId();
        String productId = productInfo.getProductId();
        String shipType = productInfo.getShipType();

        OrderTicketBody ticketBody = OrderTicketBody.of(mobile, fee, productName, memberId, productId, shipType);

        bookService.bookRoom(ticketBody, cookieValue, userInfo.getName(), productName);

    }


    private List<JsonData> getJsonData() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        List<JsonData> jsonData;
        try {
            InputStream resourceAsStream = new ClassPathResource("6.18.json").getInputStream();

            TypeReference<List<JsonData>> listTypeReference = new TypeReference<List<JsonData>>() {
            };
            jsonData = objectMapper.readValue(resourceAsStream, listTypeReference);
        } catch (Exception e) {
            log.warn("---------json解析错误---------");
            return new ArrayList<>();
        }

        LocalDateTime now = LocalDateTime.of(LocalDate.now(), LocalTime.of(10, 0));
        String format = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        return jsonData.stream()
            .filter(e -> e.getSellDateStart().equals(format))
            .collect(Collectors.toList());
    }


}
